package com.xz.spi.javassit;

import javassist.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Created by FangXz on 2017/11/8.
 */
public class JavassitDemo {
    public static void main(String[] args) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = pool.makeClass("com.xz.spi.javassit.HelloService");
        try {
            ctClass.addField(CtField.make("private String name;", ctClass));
            ctClass.addMethod(CtMethod.make("public String hello() { return \"hello \" + this.name; }", ctClass));
            ctClass.addMethod(CtMethod.make("public void setName(String name) { this.name = name; System.out.println(\"setName success\"); }", ctClass));
            ctClass.writeFile("D:\\git source\\simple-rpc\\dubbo-simplerpc");

            Class clazz = ctClass.toClass();
            Constructor constructor = clazz.getConstructor();
            Object helloService = constructor.newInstance();
            Method setName = clazz.getMethod("setName", String.class);
            Method hello = clazz.getMethod("hello");
            setName.invoke(helloService, "小泽");
            System.out.println(hello.invoke(helloService));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
